#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import mysql.connector
from db_connection import DatabaseConnection
import sys

def get_db_connection():
    """创建数据库连接"""
    db_config = {
        'host': '172.24.222.20',
        'port': 2281,
        'user': 'a_comm_prd',
        'password': 'c4F!9opd',
        'database': 'asd_lmdm_prd',
        'charset': 'utf8'
    }
    return DatabaseConnection(db_config)

def check_order_exists(cursor, table_name, wo_no):
    """检查指定表中是否存在工单号"""
    query = f"SELECT COUNT(*) as count FROM {table_name} WHERE EOOR_WO_NO = %s"
    cursor.execute(query, (wo_no,))
    result = cursor.fetchone()
    return result['count'] > 0

def get_order_data(cursor, table_name, wo_no):
    """获取指定表中的工单数据"""
    query = f"SELECT * FROM {table_name} WHERE EOOR_WO_NO = %s"
    cursor.execute(query, (wo_no,))
    return cursor.fetchone()

def get_order_items(cursor, table_name, order_no):
    """获取指定表中的工单明细数据"""
    query = f"SELECT * FROM {table_name} WHERE EOOR_ORDER_NO = %s"
    cursor.execute(query, (order_no,))
    return cursor.fetchall()

def insert_order(cursor, order_data):
    """将工单数据插入到主表"""
    # 删除自增主键，让数据库自动生成
    if 'EOOR_ID' in order_data:
        del order_data['EOOR_ID']
    
    columns = ', '.join(order_data.keys())
    placeholders = ', '.join(['%s'] * len(order_data))
    values = tuple(order_data.values())
    
    query = f"INSERT INTO eo_t_order ({columns}) VALUES ({placeholders})"
    cursor.execute(query, values)
    return cursor.lastrowid

def insert_order_item(cursor, item_data):
    """将工单明细数据插入到主表明细"""
    # 删除自增主键，让数据库自动生成
    if 'EOIT_ID' in item_data:
        del item_data['EOIT_ID']
    
    columns = ', '.join(item_data.keys())
    placeholders = ', '.join(['%s'] * len(item_data))
    values = tuple(item_data.values())
    
    query = f"INSERT INTO eo_t_order_item ({columns}) VALUES ({placeholders})"
    cursor.execute(query, values)

def sync_order(wo_no):
    """同步工单数据"""
    db = get_db_connection()
    
    try:
        with db.cursor() as cursor:
            # 检查主表是否存在该工单
            main_exists = check_order_exists(cursor, 'eo_t_order', wo_no)
            
            # 检查备份表是否存在该工单
            backup_exists = check_order_exists(cursor, 'eo_t_order_bak_20250827', wo_no)
            
            if not backup_exists:
                print(f"备份表中不存在工单号 {wo_no}")
                return
            
            if main_exists:
                print(f"主表中已存在工单号 {wo_no}，无需同步")
                return
            
            # 从备份表获取工单数据
            order_data = get_order_data(cursor, 'eo_t_order_bak_20250827', wo_no)
            if not order_data:
                print(f"无法获取备份表中的工单数据，工单号: {wo_no}")
                return
            
            # 获取工单号
            order_no = order_data.get('EOOR_ORDER_NO')
            if not order_no:
                print(f"备份表中的工单数据缺少订单号，工单号: {wo_no}")
                return
            
            # 获取备份表中的明细数据
            backup_items = get_order_items(cursor, 'eo_t_order_item_bak_20250827', order_no)
            
            # 开始事务
            with db.transaction():
                # 插入主表数据
                insert_order(cursor, order_data)
                print(f"已将工单 {wo_no} 的数据从备份表同步到主表")
                
                # 插入明细表数据
                for item in backup_items:
                    insert_order_item(cursor, item)
                
                print(f"已将工单号 {wo_no} 对应的订单号 {order_no} 的 {len(backup_items)} 条明细数据从备份表同步到主表")
    
    except Exception as e:
        print(f"同步过程中发生错误: {str(e)}")
    finally:
        db.close()

def main():
    """主函数"""
    if len(sys.argv) != 2:
        print("使用方法: python order_sync.py <工单号>")
        return
    
    wo_no = sys.argv[1]
    print(f"开始同步工单号 {wo_no} 的数据...")
    sync_order(wo_no)
    print("同步完成")

if __name__ == "__main__":
    main()